package org.ndx.majick.ui.file;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.ndx.majick.properties.Property;
import org.ndx.majick.ui.IUIProvider;

/**
 * Specialized panel used to edit a file path
 * @author Nicolas Delsaux
 *
 */
public class FilePathEditor extends JPanel {
	public static final String FILE_CHOOSER = ".fileChooser";
	private class EditPathAction extends AbstractAction implements Action {

		public EditPathAction() {
			super();
			setName("...");
		}

		/** Expected action is to open a file chooser, configured from metadata, then letting him work. */
		public void actionPerformed(ActionEvent e) {
			JFileChooser chooser = new JFileChooser(source.get());
			chooser.setName(source.getName()+IUIProvider.EDITOR+FILE_CHOOSER);
			chooser.setFileFilter(metadata.fileFilter.get());
			chooser.setMultiSelectionEnabled(false);
			chooser.setFileSelectionMode(metadata.fileSelectionMode.get());
			int returned = chooser.showDialog(FilePathEditor.this, metadata.approvedButtonText.get());
		    if(returned == JFileChooser.APPROVE_OPTION) {
		    	/* Notice here we don't care about VetoableProperty, which will do its work behind 
		    	 * the scenes. The only thing we want here is try to change. Success is managed internally.
		    	 */
	             source.set(chooser.getSelectedFile());
		     }
		}
	}

	/** text field displaying file path. As a default, this path field is always disabled. */
	private JTextField pathField;
	private Property<File> source;
	private FilePropertyMetadata metadata;
	private JButton editButton;

	public FilePathEditor(FilePropertyMetadata metadata, Property<File> source) {
		super();
		this.source = source;
		this.metadata = metadata;
		build();
	}

	private void build() {
		pathField = new JTextField();
		pathField.setEditable(false);
		AbstractViewUpdater<JTextField> pathFieldUpdater = new AbstractViewUpdater<JTextField>(pathField, metadata, source) {

			@Override
			protected void setViewText(String path) {
				viewComponent.setText(path);
			}
			
		};
		editButton = new JButton(new EditPathAction());
		setLayout(new FlowLayout(FlowLayout.LEFT));
		add(pathField);
		add(editButton);
	}

	/**
	 * When toggling enabled/disabled state, we also change the inner components ones
	 */
	@Override
	public void setEnabled(boolean enabled) {
		super.setEnabled(enabled);
		pathField.setEnabled(enabled);
		editButton.setEnabled(enabled);
	}

	public JTextField getPathField() {
		return pathField;
	}

	public JButton getEditButton() {
		return editButton;
	}
}
